package com.quickboot.system.service.impl;

import cn.hutool.core.comparator.CompareUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quickboot.common.consts.MsgConst;
import com.quickboot.common.entity.Result;
import com.quickboot.common.utils.AssertUtils;
import com.quickboot.system.entity.SysPermission;
import com.quickboot.system.entity.SysRole;
import com.quickboot.system.entity.SysUser;
import com.quickboot.system.entity.SysUserRole;
import com.quickboot.system.mapper.SysUserMapper;
import com.quickboot.system.service.SysUserRoleService;
import com.quickboot.system.service.SysUserService;
import com.quickboot.system.vo.SysUserVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 用户 接口实现类
 *
 * @author Tellsea
 * @date 2022-11-27
 */
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysUserRoleService userRoleService;

    @Override
    public Page<SysUserVo> queryList(Page page, SysUserVo entity) {
        return this.baseMapper.queryList(page, entity);
    }

    @Override
    public SysUserVo queryById(Long id) {
        return this.baseMapper.queryById(id);
    }

    @Override
    public List<SysRole> listRoleById(Long id) {
        return this.baseMapper.listRoleById(id);
    }

    @Override
    public List<SysPermission> listPermissionById(Long id) {
        return this.baseMapper.listPermissionById(id);
    }

    @Override
    public Result createUser(SysUserVo entity) {
        Long count = this.baseMapper.selectCount(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName, entity.getUserName()));
        AssertUtils.isTrue(CompareUtil.compare(count, 0L) > 0, "账号已存在");
        entity.setPassword(SecureUtil.md5(entity.getPassword()));
        this.baseMapper.insert(entity);
        handleRole(entity);
        return Result.ok(MsgConst.SAVE_SUCCESS);
    }

    @Override
    public Result updateUser(SysUserVo entity) {
        List<SysUser> userList = this.baseMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName, entity.getUserName()));
        if (!CollectionUtils.isEmpty(userList)) {
            AssertUtils.isTrue(userList.size() > 1, "存在多个异常账号");
            AssertUtils.isTrue(userList.size() == 1 && CompareUtil.compare(userList.get(0).getId(), entity.getId()) != 0, "该账号已经被使用");
        }
        this.baseMapper.updateById(entity);
        userRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, entity.getId()));
        handleRole(entity);
        return Result.ok(MsgConst.UPDATE_SUCCESS);
    }

    /**
     * 新增/更新角色公共方法
     *
     * @param entity
     */
    private void handleRole(SysUserVo entity) {
        if (!Objects.isNull(entity.getRoleIds())) {
            List<SysUserRole> roleList = new ArrayList<>();
            String[] roleIds = entity.getRoleIds().split(",");
            for (int i = 0; i < roleIds.length; i++) {
                roleList.add(new SysUserRole().setUserId(entity.getId()).setRoleId(Long.valueOf(roleIds[i])));
            }
            userRoleService.saveBatch(roleList);
        }
    }
}
